<template>
  <div class="approval-page">
    <div class="content-wrapper">
      <div class="left-content">
        <!-- 基本信息区域 -->
        <el-card class="basic-info-card">
          <h3>基本信息</h3>
          <ul class="info-list">
            <li>
              <span class="label">单据编号</span
              ><span class="value">{{ form.businessId || "-" }}</span>
            </li>
            <li>
              <span class="label">老人姓名</span
              ><span class="value">{{ elderlyInfo.name || "-" }}</span>
            </li>
            <li>
              <span class="label">老人身份证号</span
              ><span class="value">{{ elderlyInfo.idCard || "-" }}</span>
            </li>
            <li>
              <span class="label">联系方式</span
              ><span class="value">{{ elderlyInfo.contact || "-" }}</span>
            </li>
            <li>
              <span class="label">护理等级</span
              ><span class="value">{{ elderlyInfo.levelName || "-" }}</span>
            </li>
            <li>
              <span class="label">入住床位</span
              ><span class="value">{{ elderlyInfo.bedNo || "-" }}</span>
            </li>
            <li>
              <span class="label">护理员</span
              ><span class="value">{{ elderlyInfo.caregiverNameStr || "-" }}</span>
            </li>
          </ul>
        </el-card>

        <!-- 申请信息区域 -->
        <el-card class="apply-info-card">
          <h3>申请信息</h3>
          <ul class="info-list">
            <li>
              <span class="label">陪同人</span
              ><span class="value">{{
                formatCompanionType(form.companionType) || "-"
              }}</span>
            </li>
            <li>
              <span class="label">陪同人姓名</span
              ><span class="value">{{ form.companionName || "-" }}</span>
            </li>
            <li>
              <span class="label">陪同人联系方式</span
              ><span class="value">{{ form.companionPhone || "-" }}</span>
            </li>
            <li>
              <span class="label">请假周期</span
              ><span class="value">{{
                form.leaveStartTime && form.expectedEndTime 
                  ? `${formatDate(form.leaveStartTime)} 至 ${formatDate(form.expectedEndTime)}`
                  : "-"
              }}</span>
            </li>
            <li>
              <span class="label">请假天数</span
              ><span class="value">{{ form.expectedLeaveDays || "-" }}</span>
            </li>
            <li>
              <span class="label">请假原因</span
              ><span class="value">{{ form.leaveReason || "-" }}</span>
            </li>
            <li>
              <span class="label">申请人</span
              ><span class="value">huliyuanA</span>
            </li>
            <li>
              <span class="label">申请时间</span
              ><span class="value">{{ formatDate(form.createTime) || "-" }}</span>
            </li>
          </ul>
        </el-card>

        <!-- 销假记录区域 -->
        <div v-if="leaveRecord.actualReturnTime" class="leave-card-wrapper">
          <el-card class="leave-record-form">
            <h3>销假记录</h3>
            <ul>
              <li>
                <span class="label">状态：</span>
                <span class="value">{{ leaveRecord.status || "-" }}</span>
              </li>
              <li>
                <span class="label">实际返回时间：</span>
                <span class="value">{{ formatDate(leaveRecord.actualReturnTime) || "-" }}</span>
              </li>
              <li>
                <span class="label">实际请假天数：</span>
                <span class="value">{{ leaveRecord.actualLeaveDays || "-" }}</span>
              </li>
              <li>
                <span class="label">备注：</span>
                <span class="value">{{ leaveRecord.remark || "-" }}</span>
              </li>
              <li>
                <span class="label">销假人：</span>
                <span class="value">{{ leaveRecord.returnOperator || "-" }}</span>
              </li>
              <li>
                <span class="label">销假时间：</span>
                <span class="value">{{ formatDate(leaveRecord.returnTime) || "-" }}</span>
              </li>
            </ul>
          </el-card>
        </div>
      </div>

      <div class="right-content">
        <!-- 操作记录区域 -->
        <el-card class="operation-record-card">
          <h3>操作记录</h3>
          <ul class="record-list" v-if="operationRecords.length > 0">
            <li v-for="(record, index) in operationRecords" :key="index">
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>{{ record.operation }}-{{ record.step }}</p>
                  <p>{{ record.approver }} ({{ record.result }})</p>
                  <p v-if="record.opinion" class="opinion">审批意见：{{ record.opinion }}</p>
                </div>
                <div class="record-time">{{ formatDate(record.time) }}</div>
              </div>
            </li>
          </ul>
          <div v-else class="empty-record">暂无操作记录</div>
        </el-card>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <el-button @click="handleBack" size="default">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { getLeavemanage } from "@/api/leave/leavemanage";
import { listRecord } from "@/api/leave/record"; // 保留操作记录列表接口
import { getElderly } from "@/api/system/elderly"; // 老人信息接口
import useUserStore from "@/store/modules/user";

// 状态管理与路由
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const loading = ElLoading.service({ text: "加载中..." });

// 从路由参数获取关键数据（leaveId是leave_request表主键）
const leaveId = ref(route.query.leaveId); // 请假记录ID（leave_request主键）
const opinion = ref(route.query.opinion || ""); // 审批意见
const approveStatus = ref(route.query.approveStatus || ""); // 审批状态（驳回/通过）

// 数据存储
const form = ref({}); // 请假申请信息（leave_request表数据）
const elderlyInfo = ref({}); // 老人基本信息
const leaveRecord = ref({}); // 销假记录
const operationRecords = ref([]); // 操作记录列表

// 格式化工具
const formatDate = (time) => {
  if (!time) return "";
  return new Date(time).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  }).replace(/\//g, "-");
};

const formatCompanionType = (type) => {
  const typeMap = {
    家属: "家属",
    护理人员: "护理人员",
    其他: "其他",
    无: "无",
  };
  return typeMap[type] || type;
};

// 接口调用逻辑
const fetchData = async () => {
  try {
    // 1. 校验leaveId是否存在
    if (!leaveId.value || isNaN(Number(leaveId.value))) {
      ElMessage.error("缺少有效的请假记录ID");
      return;
    }

    // 2. 直接通过leaveId查询请假申请信息（leave_request表）
    const leaveRes = await getLeavemanage(leaveId.value);
    if (!leaveRes || !leaveRes.data) {
      ElMessage.error(`未查询到ID为${leaveId.value}的请假记录`);
      return;
    }
    form.value = leaveRes.data;
    console.log("请假申请信息：", form.value);

    // 3. 通过leave_request中的老人外键查询老人基本信息
    if (form.value.elderlyId) {
      const elderlyRes = await getElderly(form.value.elderlyId);
      if (elderlyRes && elderlyRes.data) {
        elderlyInfo.value = elderlyRes.data;
      } else {
        ElMessage.warning("未查询到关联的老人信息");
      }
    } else {
      ElMessage.warning("请假记录未关联老人ID");
    }

    // 4. 处理销假记录（从leave_request表中提取）
    leaveRecord.value = {
      status: form.value.pizhun || "",
      actualReturnTime: form.value.actualEndTime || "",
      actualLeaveDays: form.value.actualLeaveDays || "",
      remark: form.value.actualReturnRemark || "",
      returnOperator: form.value.returnOperator || "",
      returnTime: form.value.returnTime || "",
    };

    // 5. 构建操作记录（包含路由参数中的审批状态和意见）
    // 5.1 先查询历史审批记录
    let recordRes = null;
    if (form.value.businessId) {
      recordRes = await listRecord({
        bussniessId: form.value.businessId,
        type: "请假",
      });
    }

    // 5.2 格式化历史记录
    const historyRecords = recordRes?.data?.rows?.map(item => ({
      operation: item.auditStatus === "通过" ? "审批通过" : "审批驳回",
      step: item.currentStep || "",
      approver: item.approverName || "",
      result: item.auditStatus || "",
      opinion: item.opinion || "",
      time: item.createTime || "",
    })) || [];

    // 5.3 增加当前审批记录（从路由参数获取）
    const currentApprovalRecord = {
      operation: approveStatus.value === "通过" ? "审批通过" : "审批驳回",
      step: "最终审批",
      approver: userStore.nickName || "系统", // 当前登录用户
      result: approveStatus.value || "未知状态",
      opinion: opinion.value || "无意见",
      time: new Date().toISOString(), // 当前时间
    };

    // 5.4 增加发起申请记录
    const createRecord = {
      operation: "发起申请",
      step: form.value.currentStep || "申请请假",
      approver: form.value.creatorName || "",
      result: "已发起",
      time: form.value.createTime || "",
    };

    // 组合所有记录并按时间排序
    operationRecords.value = [
      createRecord,
      ...historyRecords,
      currentApprovalRecord
    ].sort((a, b) => new Date(a.time) - new Date(b.time));

  } catch (error) {
    console.error("数据获取失败：", error);
    ElMessage.error("加载详情失败，请重试");
  } finally {
    loading.close();
  }
};

// 页面挂载时加载数据
onMounted(() => {
  console.log("路由参数：", route.query);
  console.log("获取到的leaveId：", leaveId.value);
  if (leaveId.value) {
    fetchData();
  } else {
    ElMessage.error("缺少leaveId参数");
    loading.close();
  }
});

// 返回按钮
const handleBack = () => {
  router.back();
};
</script>

<style scoped>
/* 样式保持不变 */
.approval-page {
  padding: 20px;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-content {
  flex: 2;
}

.right-content {
  flex: 1;
}

.basic-info-card,
.apply-info-card,
.operation-record-card {
  margin-bottom: 20px;
}

.operation-record-card {
  height: 440px;
  overflow: hidden;
  position: relative;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.label {
  width: 120px;
  text-align: right;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 380px;
  overflow-y: auto;
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 14px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
}

.record-item:last-child {
  border-bottom: none;
}

.record-icon {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #409eff;
  margin-right: 10px;
  margin-top: 5px;
}

.record-content {
  flex: 1;
  color: #333;
}

.record-content p {
  margin: 4px 0;
}

.record-content .opinion {
  color: #666;
  font-size: 13px;
  padding-left: 5px;
  border-left: 2px solid #eee;
}

.record-time {
  width: 150px;
  text-align: right;
  color: #999;
  font-size: 13px;
}

.bottom-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.empty-record {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.leave-record-form {
  margin-bottom: 20px;
}

.leave-record-form h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.leave-record-form ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.leave-record-form li {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.leave-card-wrapper {
  display: block;
  margin-bottom: 20px;
}
</style>